package com.cares.fw.jms.utils;

import java.io.Serializable;
import java.util.Properties;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

import com.cares.fw.springframework.utils.SpringUtils;

public class JMSUtils {
	public static void send(final String senderName, final Serializable serObj) {
		JmsTemplate jmsTemplate = SpringUtils.getBean(senderName, JmsTemplate.class);
		send(jmsTemplate, serObj);
	}
	
	public static void send(final JmsTemplate jmsTemplate, final Serializable serObj) {
		jmsTemplate.send(new MessageCreator(){
			public Message createMessage(Session session) throws JMSException {
				return session.createObjectMessage(serObj);
			}
		});
	}
	
	// --- FIXME -------------------------------------------------------------------------------------------------------------------
	public Context createContext() throws NamingException {
		Properties env = new Properties();
		env.put("java.naming.factory.initial", "weblogic.jndi.WLInitialContextFactory");
		env.put("java.naming.provider.url", "t3://172.21.120.97:7001");
		env.put("java.naming.factory.url.pkgs", "weblogic.jndi.factories");
		
		return new InitialContext(env);
	}
	
	public Object lookup(final String jndiName) throws NamingException {
		return createContext().lookup(jndiName);
	}

	public void send(final String cfJndiName, final String queueJndiName, final Serializable serObj) throws NamingException, JMSException {
		ConnectionFactory cf = (ConnectionFactory) lookup(cfJndiName);
		Destination destination = (Destination) lookup(queueJndiName);
		
		Connection conn = cf.createConnection();
		Session sess = conn.createSession(true, Session.AUTO_ACKNOWLEDGE);
		MessageProducer mp = sess.createProducer(destination);
		Message message = sess.createObjectMessage(serObj);
		mp.send(message);
	}
}
